<template>
  <div class="activity-stats-container">
    <el-card shadow="never">
      <!-- 数据概览 -->
      <div class="stats-header">
        <h2><el-icon><DataLine /></el-icon> 用户活跃度统计</h2>
        <div class="header-actions">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="fetchActivityStats"
          />
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>

      <!-- 关键指标卡片 -->
      <el-row :gutter="20" class="stats-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <div class="card-title">日活跃用户(DAU)</div>
              <div class="card-value">{{ statsSummary.dau }}</div>
              <div class="card-compare">
                <span :class="statsSummary.dauTrend >= 0 ? 'up' : 'down'">
                  <el-icon :name="statsSummary.dauTrend >= 0 ? 'Top' : 'Bottom'" />
                  {{ Math.abs(statsSummary.dauTrend) }}%
                </span>
                较昨日
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <div class="card-title">周活跃用户(WAU)</div>
              <div class="card-value">{{ statsSummary.wau }}</div>
              <div class="card-compare">
                <span :class="statsSummary.wauTrend >= 0 ? 'up' : 'down'">
                  <el-icon :name="statsSummary.wauTrend >= 0 ? 'Top' : 'Bottom'" />
                  {{ Math.abs(statsSummary.wauTrend) }}%
                </span>
                较上周
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <div class="card-title">月活跃用户(MAU)</div>
              <div class="card-value">{{ statsSummary.mau }}</div>
              <div class="card-compare">
                <span :class="statsSummary.mauTrend >= 0 ? 'up' : 'down'">
                  <el-icon :name="statsSummary.mauTrend >= 0 ? 'Top' : 'Bottom'" />
                  {{ Math.abs(statsSummary.mauTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="card-content">
              <div class="card-title">平均使用时长</div>
              <div class="card-value">{{ statsSummary.avgDuration }}分钟</div>
              <div class="card-compare">
                <span :class="statsSummary.durationTrend >= 0 ? 'up' : 'down'">
                  <el-icon :name="statsSummary.durationTrend >= 0 ? 'Top' : 'Bottom'" />
                  {{ Math.abs(statsSummary.durationTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 活跃趋势图 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <div class="chart-header">
              <h3>活跃用户趋势</h3>
              <el-radio-group v-model="activeChartType" size="small">
                <el-radio-button label="daily">日趋势</el-radio-button>
                <el-radio-button label="weekly">周趋势</el-radio-button>
                <el-radio-button label="monthly">月趋势</el-radio-button>
              </el-radio-group>
            </div>
            <div class="chart-container">
              <div ref="activeTrendChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 用户分布 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <h3>用户活跃分布</h3>
            <div class="chart-container">
              <div ref="userDistributionChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 用户行为分析 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 行为漏斗图 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <h3>用户行为漏斗</h3>
            <div class="chart-container">
              <div ref="behaviorFunnelChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 时段分布 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <h3>活跃时段分布</h3>
            <div class="chart-container">
              <div ref="hourlyActiveChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 活跃用户列表 -->
      <el-card shadow="hover" class="user-list-card">
        <div class="list-header">
          <h3>高活跃用户排行</h3>
          <el-input
              v-model="userSearch"
              placeholder="搜索用户名"
              style="width: 200px"
              clearable
              @clear="fetchActiveUsers"
              @keyup.enter="fetchActiveUsers"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <el-table
            :data="activeUsers"
            style="width: 100%"
            v-loading="userLoading"
            @sort-change="handleSortChange"
        >
          <el-table-column prop="rank" label="排名" width="80" sortable />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="loginCount" label="登录次数" width="120" sortable />
          <el-table-column prop="viewCount" label="浏览房源" width="120" sortable />
          <el-table-column prop="duration" label="使用时长(分)" width="140" sortable />
          <el-table-column prop="lastActive" label="最后活跃" width="160" sortable />
          <el-table-column label="活跃度" sortable>
            <template #default="{ row }">
              <el-progress
                  :percentage="row.activityScore"
                  :color="getActivityColor(row.activityScore)"
                  :format="formatActivityScore"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewUserDetail(row.id)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="userPage"
            v-model:page-size="userPageSize"
            :total="userTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="fetchActiveUsers"
            @current-change="fetchActiveUsers"
            style="margin-top: 20px"
        />
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { DataLine, Download, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 日期范围选择
const dateRange = ref(['2023-06-01', '2023-06-30'])

// 数据概览
const statsSummary = ref({
  dau: 0,
  wau: 0,
  mau: 0,
  avgDuration: 0,
  dauTrend: 0,
  wauTrend: 0,
  mauTrend: 0,
  durationTrend: 0
})

// 图表相关
const activeChartType = ref('daily')
const activeTrendChart = ref(null)
const userDistributionChart = ref(null)
const behaviorFunnelChart = ref(null)
const hourlyActiveChart = ref(null)

// 活跃用户列表
const userSearch = ref('')
const userPage = ref(1)
const userPageSize = ref(10)
const userTotal = ref(0)

// 模拟所有活跃用户数据
const allActiveUsers = ref([
  {
    id: 1,
    rank: 1,
    username: '张活跃',
    loginCount: 28,
    viewCount: 156,
    duration: 245,
    lastActive: '2023-06-30 22:45:10',
    activityScore: 92
  },
  {
    id: 2,
    rank: 2,
    username: '李频繁',
    loginCount: 25,
    viewCount: 132,
    duration: 210,
    lastActive: '2023-06-30 21:30:45',
    activityScore: 88
  },
  {
    id: 3,
    rank: 3,
    username: '王经常',
    loginCount: 22,
    viewCount: 118,
    duration: 195,
    lastActive: '2023-06-30 20:15:30',
    activityScore: 85
  },
  {
    id: 4,
    rank: 4,
    username: '赵活跃',
    loginCount: 20,
    viewCount: 105,
    duration: 180,
    lastActive: '2023-06-30 19:00:20',
    activityScore: 82
  },
  {
    id: 5,
    rank: 5,
    username: '孙频繁',
    loginCount: 18,
    viewCount: 98,
    duration: 165,
    lastActive: '2023-06-30 18:30:15',
    activityScore: 79
  },
  {
    id: 6,
    rank: 6,
    username: '周经常',
    loginCount: 16,
    viewCount: 85,
    duration: 150,
    lastActive: '2023-06-30 17:45:10',
    activityScore: 76
  },
  {
    id: 7,
    rank: 7,
    username: '吴活跃',
    loginCount: 15,
    viewCount: 78,
    duration: 140,
    lastActive: '2023-06-30 16:30:30',
    activityScore: 73
  },
  {
    id: 8,
    rank: 8,
    username: '郑频繁',
    loginCount: 14,
    viewCount: 72,
    duration: 130,
    lastActive: '2023-06-30 15:15:20',
    activityScore: 70
  },
  {
    id: 9,
    rank: 9,
    username: '钱经常',
    loginCount: 13,
    viewCount: 65,
    duration: 120,
    lastActive: '2023-06-30 14:00:10',
    activityScore: 67
  },
  {
    id: 10,
    rank: 10,
    username: '孙活跃',
    loginCount: 12,
    viewCount: 58,
    duration: 110,
    lastActive: '2023-06-30 13:30:45',
    activityScore: 64
  },
  {
    id: 11,
    rank: 11,
    username: '冯活跃',
    loginCount: 11,
    viewCount: 52,
    duration: 105,
    lastActive: '2023-06-30 12:45:30',
    activityScore: 61
  },
  {
    id: 12,
    rank: 12,
    username: '陈频繁',
    loginCount: 10,
    viewCount: 48,
    duration: 95,
    lastActive: '2023-06-30 11:30:20',
    activityScore: 58
  },
  {
    id: 13,
    rank: 13,
    username: '褚经常',
    loginCount: 9,
    viewCount: 42,
    duration: 88,
    lastActive: '2023-06-30 10:15:10',
    activityScore: 55
  },
  {
    id: 14,
    rank: 14,
    username: '卫活跃',
    loginCount: 8,
    viewCount: 38,
    duration: 80,
    lastActive: '2023-06-30 09:00:45',
    activityScore: 52
  },
  {
    id: 15,
    rank: 15,
    username: '蒋频繁',
    loginCount: 7,
    viewCount: 35,
    duration: 75,
    lastActive: '2023-06-30 08:30:30',
    activityScore: 49
  },
  {
    id: 16,
    rank: 16,
    username: '沈经常',
    loginCount: 6,
    viewCount: 32,
    duration: 70,
    lastActive: '2023-06-30 07:45:20',
    activityScore: 46
  },
  {
    id: 17,
    rank: 17,
    username: '韩活跃',
    loginCount: 5,
    viewCount: 28,
    duration: 65,
    lastActive: '2023-06-30 06:30:10',
    activityScore: 43
  },
  {
    id: 18,
    rank: 18,
    username: '杨频繁',
    loginCount: 4,
    viewCount: 25,
    duration: 60,
    lastActive: '2023-06-30 05:15:45',
    activityScore: 40
  },
  {
    id: 19,
    rank: 19,
    username: '朱经常',
    loginCount: 3,
    viewCount: 22,
    duration: 55,
    lastActive: '2023-06-30 04:00:30',
    activityScore: 37
  },
  {
    id: 20,
    rank: 20,
    username: '秦活跃',
    loginCount: 2,
    viewCount: 18,
    duration: 50,
    lastActive: '2023-06-30 03:30:20',
    activityScore: 34
  }
])

// 活跃用户列表（计算属性，根据搜索条件过滤）
const activeUsers = computed(() => {
  let filtered = allActiveUsers.value

  // 应用搜索过滤
  if (userSearch.value) {
    filtered = filtered.filter(item =>
        item.username.includes(userSearch.value)
    )
  }

  // 更新总数
  userTotal.value = filtered.length

  // 应用分页
  const startIndex = (userPage.value - 1) * userPageSize.value
  const endIndex = startIndex + userPageSize.value
  return filtered.slice(startIndex, endIndex)
})

// 用户加载状态
const userLoading = ref(false)

// 模拟活跃度统计数据
const mockActivityStats = {
  summary: {
    dau: 12800,
    wau: 56000,
    mau: 180000,
    avgDuration: 35.5,
    dauTrend: 8.5,
    wauTrend: 5.2,
    mauTrend: 3.8,
    durationTrend: 12.3
  },
  trend: {
    dates: ['6.1', '6.2', '6.3', '6.4', '6.5', '6.6', '6.7', '6.8', '6.9', '6.10'],
    dau: [10500, 11200, 11800, 12100, 12500, 12800, 13200, 13500, 13800, 14200],
    wau: [45000, 48000, 50000, 52000, 54000, 56000, 58000, 60000, 62000, 64000],
    mau: [150000, 155000, 160000, 165000, 170000, 175000, 180000, 185000, 190000, 195000]
  },
  distribution: {
    '北京': 35,
    '上海': 25,
    '广州': 15,
    '深圳': 12,
    '其他': 13
  },
  funnel: {
    steps: ['浏览房源', '收藏房源', '预约看房', '签约入住'],
    rates: [100, 35, 15, 8]
  },
  hourly: [
    500, 300, 200, 150, 100, 120, 300, 800, 1200, 1500,
    1800, 2000, 1900, 1800, 2200, 2500, 2800, 3000, 2500,
    2000, 1800, 1500, 1000, 800
  ]
}

// 获取活跃度统计数据（使用死数据）
const fetchActivityStats = () => {
  // 模拟API请求延迟
  setTimeout(() => {
    statsSummary.value = mockActivityStats.summary

    // 渲染图表
    nextTick(() => {
      renderActiveTrendChart(mockActivityStats.trend)
      renderUserDistributionChart(mockActivityStats.distribution)
      renderBehaviorFunnelChart(mockActivityStats.funnel)
      renderHourlyActiveChart(mockActivityStats.hourly)
    })
  }, 500)
}

// 获取活跃用户列表（使用死数据）
const fetchActiveUsers = () => {
  userLoading.value = true

  // 模拟API请求延迟
  setTimeout(() => {
    // 数据已通过计算属性自动处理
    userLoading.value = false
  }, 500)
}

// 渲染活跃趋势图
const renderActiveTrendChart = (data) => {
  if (!activeTrendChart.value) return

  const chart = echarts.init(activeTrendChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['日活跃用户', '周活跃用户', '月活跃用户']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value',
      name: '用户数'
    },
    series: [
      {
        name: '日活跃用户',
        type: 'line',
        smooth: true,
        data: data.dau
      },
      {
        name: '周活跃用户',
        type: 'line',
        smooth: true,
        data: data.wau
      },
      {
        name: '月活跃用户',
        type: 'line',
        smooth: true,
        data: data.mau
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 渲染用户分布图
const renderUserDistributionChart = (data) => {
  if (!userDistributionChart.value) return

  const chart = echarts.init(userDistributionChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.entries(data).map(([name, value]) => ({
          name,
          value
        }))
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 渲染行为漏斗图
const renderBehaviorFunnelChart = (data) => {
  if (!behaviorFunnelChart.value) return

  const chart = echarts.init(behaviorFunnelChart.value)
  const option = {
    title: {
      text: '用户行为转化率',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}%'
    },
    toolbox: {
      feature: {
        dataView: { readOnly: false },
        restore: {},
        saveAsImage: {}
      }
    },
    legend: {
      data: data.steps,
      bottom: 10
    },
    series: [
      {
        name: '行为漏斗',
        type: 'funnel',
        left: '10%',
        top: 60,
        bottom: 60,
        width: '80%',
        min: 0,
        max: 100,
        minSize: '0%',
        maxSize: '100%',
        sort: 'descending',
        gap: 2,
        label: {
          show: true,
          position: 'inside'
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          label: {
            fontSize: 20
          }
        },
        data: data.steps.map((step, index) => ({
          value: data.rates[index],
          name: step
        }))
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 渲染时段分布图
const renderHourlyActiveChart = (data) => {
  if (!hourlyActiveChart.value) return

  const chart = echarts.init(hourlyActiveChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 24}, (_, i) => `${i}:00`)
    },
    yAxis: {
      type: 'value',
      name: '活跃用户数'
    },
    series: [
      {
        name: '活跃用户',
        type: 'bar',
        data: data,
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#c23531','#2f4554','#61a0a8','#d48265',
              '#91c7ae','#749f83','#ca8622','#bda29a'
            ]
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出功能已触发，实际项目中会生成并下载数据')
}

// 查看用户详情
const viewUserDetail = (userId) => {
  ElMessage.info(`查看用户详情: ID=${userId}`)
}

// 表格排序变化
const handleSortChange = ({ column, prop, order }) => {
  console.log('排序变化', prop, order)
  // 在实际项目中，这里可以根据排序条件重新获取数据
}

// 获取活跃度颜色
const getActivityColor = (score) => {
  if (score >= 80) return '#67c23a'
  if (score >= 60) return '#e6a23c'
  if (score >= 30) return '#f56c6c'
  return '#909399'
}

// 格式化活跃度显示
const formatActivityScore = (percentage) => {
  return `${percentage}%`
}

// 初始化加载数据
onMounted(() => {
  fetchActivityStats()
  fetchActiveUsers()
})
</script>

<style scoped lang="scss">
.activity-stats-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    display: flex;
    align-items: center;
    margin: 0;

    .el-icon {
      margin-right: 8px;
      font-size: 24px;
      color: #409eff;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .card-content {
    padding: 15px;

    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .card-compare {
      font-size: 12px;
      color: #909399;

      .up {
        color: #67c23a;
      }

      .down {
        color: #f56c6c;
      }

      .el-icon {
        font-size: 12px;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-container {
  height: 350px;
}

.user-list-card {
  margin-top: 20px;

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}
</style>